<?php
// mod文件只能被入口文件引用，不能直接访问
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

// 查询 儿童故事 下级的所有菜单！
$story_main_nav = array();
$main_nav_ids = array();
$sql = " select * from t_topic t where t.parent_id = 6 order by parent_id,id,layer,order_num ";
$query = DB::query($sql);
while($row = DB::fetch($query)) {
	$story_main_nav[] = $row;
	$main_nav_ids[] = $row['id'];
}
DB::free_result($query);

$pid = $_G["gp_pid"];
if (!isset($pid) || !in_array($pid, $main_nav_ids)) {
	$pid = $main_nav_ids[0];
}

$topic_title = $subnav_title = $story_main_nav[0]['title'];
foreach ($story_main_nav as $main_nav) {
	if ($pid == $main_nav['id']){
		$topic_title = $subnav_title = $main_nav['title'];
		break;
	}
}

if(isset($pid)){
	$article_topic_ids = array();
	$story_sub_nav = array();
	$sql = " select * from t_topic t where t.parent_id = $pid order by parent_id,id,layer,order_num ";
	$query = DB::query($sql);
	while($row = DB::fetch($query)) {
		$sub_nav_cat = $subnav_title.'&nbsp;=&gt;&nbsp;'.$row['title'];

		$story_sub_nav[$sub_nav_cat] = array();
		$sub_sql = 'select * from t_topic t where t.parent_id ='. $row['id'].' order by parent_id,id,layer,order_num ';
		$sub_query = DB::query($sub_sql);
		while($sub_row = DB::fetch($sub_query)) {
			$story_sub_nav[$sub_nav_cat][] = $sub_row;
			$article_topic_ids[] = $sub_row['id'];
		}
		DB::free_result($sub_query);
	}
	DB::free_result($query);

	// 找到第一个直接挂着文章的topic
	$tid = $_G["gp_tid"];
	if ( !isset($tid) || !in_array($tid, $article_topic_ids)){
		$tid = $article_topic_ids[0];
	}
	if(isset($tid)){
		$article_list = array();
		$article_ids = array();
		$sql = "select id,topic_id,title,sub_title,author_name,summary from t_article where topic_id = $tid order by id ";
		$query = DB::query($sql);
		while($row = DB::fetch($query)) {
			$article_list[] = $row;
			$article_ids[] = $row['id'];
		}
		DB::free_result($query);

		$aid = $_G["gp_aid"];
		if (!isset($aid) || !in_array($aid, $article_ids)) {
			$aid = $article_ids[0];
		}

		$article_title =  $article_list[0]['title'];
		foreach ($article_list as $article) {
			if ($aid == $article['id']){
				$article_title =  $article['title'];
				break;
			}
		}


		// 该topic文章数量不为空。
		$show_pre = false;
		$show_next = false;
		if(count($article_list) > 0 ){
			if ($aid > $article_ids[0] ){
				$show_pre = true;
			}
			if ($aid < $article_ids[count($article_ids) - 1] ){
				$show_next = true;
			}
		}

		$pre_aid = (intval($aid) - 1);
		$next_aid = (intval($aid) + 1 );


		if(isset($aid)){
			$sql = " select * from t_paragraph where article_id = $aid order by id asc ";
			$paragraph_list = array();
			$query = DB::query($sql);
			while($row = DB::fetch($query)) {
				$paragraph_list[] = $row;
			}
			DB::free_result($query);
		}
	}
}

if ($pid == 26 || $pid == 27){
	include_once template("know/vstory2");
}
else {
	include_once template("know/vstory");
}
?>